﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using Ionic.Zip;

namespace XDA_ROM_Hub
{
    public partial class progress : Form
    {
        private Thread thrDownload;
        private Stream strResponse;
        private Stream strLocal;
        private HttpWebRequest webRequest;
        private HttpWebResponse webResponse;
        private static int PercentProgress;
        private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes);
        bool goPause = false;

        public progress()
        {
            InitializeComponent();
            UserClosing = false;
            this.buttonExit.Click += new EventHandler(buttonExit_Click);
            this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
        
            
        }
        public bool UserClosing { get; set; }

        void buttonExit_Click(object sender, EventArgs e)
        {
            UserClosing = true;
            cencelbtn();
        }

        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            switch (e.CloseReason)
            {
                case CloseReason.ApplicationExitCall:
                    break;
                case CloseReason.FormOwnerClosing:
                    break;
                case CloseReason.MdiFormClosing:
                    break;
                case CloseReason.None:
                    break;
                case CloseReason.TaskManagerClosing:
                    break;
                case CloseReason.UserClosing:
                    if (UserClosing)
                    {
                        cencelbtn();
                    }
                    else
                    {
                        cencelbtn();
                    }
                    break;
                case CloseReason.WindowsShutDown:
                    break;
                default:
                    break;
            }
        }

        public void cencelbtn()
        {
        	try{
        	thrDownload.Abort();
            webResponse.Close();
            strResponse.Close();
            strLocal.Close();
            prgDownload.Value = 0;
            lblProgress.Text = "Download Stopped";
            btnPauseResume.Enabled = false;
        	}
        	catch{}
        	this.Hide();

        }
        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (thrDownload != null && thrDownload.ThreadState == ThreadState.Running)
            {
                MessageBox.Show("A download is already running. Please either the stop the current download or await for its completion before starting a new one.", "Download in progress", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                lblProgress.Text = "Download Starting";
                thrDownload = new Thread(new ParameterizedThreadStart(Download));
                thrDownload.Start(0);
                btnPauseResume.Enabled = true;
                btnPauseResume.Text = "Pause";
            }
        }

        private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
        {
            PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
             prgDownload.Value = PercentProgress;
            lblProgress.Text = "Downloaded " + BytesRead / 1048576 + "MB out of " + TotalBytes / 1048576  + "MB (" + PercentProgress + "%)";
            if (PercentProgress == 100)
            {
                unpackgb.Enabled = true;
                groupBox1.Enabled = false;
            }
            else
            {
                button1.Enabled = false;
            }
        }

        private void Download(object startPoint)
        {
            try
            {
                int startPointInt = Convert.ToInt32(startPoint);
                webRequest = (HttpWebRequest)WebRequest.Create(txtUrl.Text);
                webRequest.AddRange(startPointInt);

                webRequest.Credentials = CredentialCache.DefaultCredentials;
                
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                
                Int64 fileSize = webResponse.ContentLength;
                
                strResponse = webResponse.GetResponseStream();

                if (startPointInt == 0)
                {
                    strLocal = new FileStream(txtPath.Text, FileMode.Create, FileAccess.Write, FileShare.None);
                }
                else
                {
                    strLocal = new FileStream(txtPath.Text, FileMode.Append, FileAccess.Write, FileShare.None);
                }
                
                int bytesSize = 0;
                byte[] downBuffer = new byte[2048];

                while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                {
                    strLocal.Write(downBuffer, 0, bytesSize);
                    this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize + startPointInt });

                    if (goPause == true)
                    {
                        break;
                    }
                }
            }
            finally
            {
                strResponse.Close();
                strLocal.Close();
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                thrDownload.Abort();
                webResponse.Close();
                strResponse.Close();
                strLocal.Close();
                prgDownload.Value = 0;
                lblProgress.Text = "Download Stopped";
                btnPauseResume.Enabled = false;
            }
        }

        private void btnPauseResume_Click(object sender, EventArgs e)
        {
            if (thrDownload != null)
            {
                if (btnPauseResume.Text == "Pause")
                {
                    goPause = true;

                    btnPauseResume.Text = "Resume";

                    webResponse.Close();
                    strResponse.Close();
                    strLocal.Close();
                    thrDownload.Abort();
                }
                else
                {
                    goPause = false;

                    btnPauseResume.Text = "Pause";

                    long startPoint = 0;

                    if (File.Exists(txtPath.Text))
                    {
                        startPoint = new FileInfo(txtPath.Text).Length;
                    }
                    else
                    {
                        MessageBox.Show("The file you choosed to resume doesn't exist.", "Could not resume", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    lblProgress.Text = "Download Resuming";
                    thrDownload = new Thread(new ParameterizedThreadStart(Download));
                    thrDownload.Start(startPoint);
                    btnPauseResume.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show("A download does not appear to be in progress.", "Could not pause", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StockRomInstall StockRomInstall = new StockRomInstall();
            StockRomInstall.Show();
            this.Hide();

        }

        private void Extract()
        {
            string zipToUnpack = txtPath.Text;
            string ftfName = zipToUnpack.Replace(".zip", ".ftf");
            string unpackDirectory = @"C:\Flashtool\firmwares\";


            using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
            {
                foreach (ZipEntry e in zip1)
                {
                    e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
                    label2.Text = "Done! Please continue.";
                    button1.Enabled = true;
                    unpackgb.Enabled = false;
                }
            }

        }

       

        private void unpackbtn_Click(object sender, EventArgs e)
        {
            try
            {
                unpackbtn.Text = "Unpacking...";
                label2.Text = "Please Wait... This will take a while.";
            }
            finally
            {
                bool EnableGuide = Properties.Settings.Default.EnableGuide;
                if (EnableGuide == true)
                {
                    MessageBox.Show("You need to unpack the zip file you just downloaded", "Guide", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                Extract();
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            StockRom sr = new StockRom();
            sr.Show();
            this.Hide();

        }

        private void progress_Load(object sender, EventArgs e)
        {
            if (File.Exists(@"C:\Flashtool\Firmwares\" + this.Text + ".zip"))
            {
                groupBox1.Enabled = false;
                lblProgress.Text = "Already downloaded.";
                button1.Enabled = true;
            }
            if (File.Exists(@"C:\Flashtool\Firmwares\" + this.Text + ".ftf"))
            {
                unpackgb.Enabled = false;
                label2.Text = "Already unpacked";
                button1.Enabled = true;
            }
        }
    }
}
